<?php
// Copyright 2019 Hackware SpA <human@hackware.cl>
// "Hackware Web Services Core" is released under the MIT License terms.

namespace Hawese\Core\Http\Controllers;

use Hawese\Core\User;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth', ['except' => ['signup', 'login', 'emailToken']]);
    }

    public function whoami(Request $request)
    {
        return $request->user();
    }

    public function signup(Request $request)
    {
        // FIXME: This is a half cooked function in a hurry, plz finish it
        // FIXME: uid shouldn't exist!
        $user = new User([
            'uid' => $request->input('uid'),
            'email' => $request->input('email', $request->input('uid')),
        ]);

        try {
            $user->insert();
        } catch (\Illuminate\Database\QueryException $e) {
            if ($e->getCode() === '23000') {
                return false;
            }
            throw $e;
        }

        if ($request->input('return_token')) {
            return $user->generateHumanToken();
        }
        return $user;
    }


    public function login(Request $request): User
    {
        // TODO: return a message if app('auth')->check() is true?

        $this->validate($request, [
            'username' => 'required',
            'password' => 'required'
        ]);

        return User::loginByPassword(
            $request->input('username'),
            $request->input('password'),
            $request->filled('remember')
        );
    }

    public function logout(Request $request)
    {
        return $request->user()->logout() ? 'true' : 'false';
    }

    public function emailToken(Request $request)
    {
        if ($request->has('origin_url')) {
            $origin_url = $request->input('origin_url');
        } else {
            $referer = parse_url($request->server->get('HTTP_REFERER'));
            $origin_url = strtr(
                '$scheme://$host$port',
                [
                    '$scheme' => $referer['scheme'],
                    '$host' => $referer['host'],
                    '$port' => array_key_exists('port', $referer)
                        ? ':' . $referer['port']
                        : ''
                ]
            );
        }

        return User::emailToken(
            $request->input('username'),
            $origin_url,
            $request->input('redirect_to')
        );
    }
}
